<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Buy extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
		$userData = $this->session->all_userData();
		if (!isset($userData['logged_in']) || !$userData['logged_in']){
			redirect('./');
		}
		$this->load->model('uploking_users_m');
		$this->load->model('uploking_packages_m');
		$this->load->model('uploking_user_packages_m');
		
		$this->load->library(array('keywords/keywords'));
		$this->lang->load('uploking');
		$this->load->helper('uploking');
	}

	// blog/page/x also routes here
	public function index()
	{
		if(!($selectedPackage = $this->input->post('package'))){
			$selectedPackage = 1;
		}
		$packageList = $this->uploking_packages_m->get_all();
		
		$userData = $this->session->all_userData();
		$user = $this->uploking_users_m->get($userData['account']['user_id']);
		if ($this->input->post('buy_package_request')){
			if($selectedPackage){
				$result = array();
				$result['selectedPackage'] = $selectedPackage;
				$package = $this->uploking_packages_m->get($selectedPackage);
				if($package){
					$currentPackage = $this->uploking_user_packages_m->where('status', 2)->get_by('user_id', $user->id);
					if($currentPackage){
						$penddingPackage = $this->uploking_user_packages_m->where('status', 1)->order_by('end_date', 'DESC')->get_by('user_id', $user->id);
						if($penddingPackage){
							$startDate = getNextDayTimeStamp($penddingPackage->end_date, 1);
							$status = 1;
						}else{
							$startDate = getNextDayTimeStamp($currentPackage->end_date, 1);
							$status = 1;
						}
					}else{
						$startDate = time();
						$status = 2;
					}
					$this->uploking_user_packages_m->insert(array(
						'user_id'		=> $user->id,
						'package_id'	=> $selectedPackage,
						'start_date'	=> $startDate,
						'end_date'		=> getNextMonthTimeStamp($startDate, $package->month),
						'status'		=> $status,
						'buy_time'		=> time()
					));
					$result['result']	= true;
					$result['message']	= lang('uploking_package_select_package_success_label');
				}else{
					$result['result']	= false;
					$result['message']	= lang('uploking_package_select_package_required_label');
				}
			}else{
				$result['result']	= false;
				$result['message']	= lang('uploking_package_select_package_required_label');
			}
			echo json_encode($result);
		}else{
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			$this->template
				->title($this->module_details['name'])
				->set('selectedPackage', $selectedPackage)
				->set('user', $user)
				->set('packageList', $packageList)
				->build('buy', $this->data);
		}
	}
}
